<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="https://fonts.cat.net/css?family=Lato:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/lion_fa.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/lion_fa.ico?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JavaScript,前端,">










<meta name="description" content="本系列文章旨在记录自己平时使用到的javascript技巧，作为一个知识的积累，也方便日后翻阅。   实现base64解码  1234567891011121314151617181920212223242526function base64_decode(data)&amp;#123;    var b64 = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr">
<meta name="keywords" content="JavaScript,前端">
<meta property="og:type" content="article">
<meta property="og:title" content="JS原生技巧手记(一)">
<meta property="og:url" content="http://loren.gitee.io/blog/2016/06/16/技术/JS技巧手记（一）/index.html">
<meta property="og:site_name" content="Geron Zhang的碎碎念">
<meta property="og:description" content="本系列文章旨在记录自己平时使用到的javascript技巧，作为一个知识的积累，也方便日后翻阅。   实现base64解码  1234567891011121314151617181920212223242526function base64_decode(data)&amp;#123;    var b64 = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-05-07T15:48:13.849Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JS原生技巧手记(一)">
<meta name="twitter:description" content="本系列文章旨在记录自己平时使用到的javascript技巧，作为一个知识的积累，也方便日后翻阅。   实现base64解码  1234567891011121314151617181920212223242526function base64_decode(data)&amp;#123;    var b64 = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://loren.gitee.io/blog/2016/06/16/技术/JS技巧手记（一）/">





  <title>JS原生技巧手记(一) | Geron Zhang的碎碎念</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c17a01cf17d1b4db888987342f5b01cb";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Geron Zhang的碎碎念</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Slowly&&Forward</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://loren.gitee.io/blog/blog/2016/06/16/技术/JS技巧手记（一）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Geron Zhang">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Geron Zhang的碎碎念">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JS原生技巧手记(一)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-06-16T15:35:35+08:00">
                2016-06-16
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/技术/" itemprop="url" rel="index">
                    <span itemprop="name">技术</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2016/06/16/技术/JS技巧手记（一）/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/blog/2016/06/16/技术/JS技巧手记（一）/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/blog/2016/06/16/技术/JS技巧手记（一）/" class="leancloud_visitors" data-flag-title="JS原生技巧手记(一)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote>
<p>本系列文章旨在记录自己平时使用到的javascript技巧，作为一个知识的积累，也方便日后翻阅。</p>
</blockquote>
<ol>
<li>实现base64解码</li>
</ol>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">function base64_decode(<span class="keyword">data</span>)&#123;</span><br><span class="line">    <span class="keyword">var</span> b64 = <span class="string">"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="</span>;</span><br><span class="line">    <span class="keyword">var</span> o1, o2, o3, h1, h2, h3, h4, bits, i = <span class="number">0</span>,ac = <span class="number">0</span>,dec = <span class="string">""</span>,tmp_arr = [];</span><br><span class="line">    <span class="keyword">if</span> (!<span class="keyword">data</span>) &#123; <span class="keyword">return</span> <span class="keyword">data</span>; &#125;</span><br><span class="line">    <span class="keyword">data</span> += <span class="string">''</span>;</span><br><span class="line">    <span class="keyword">do</span> &#123;</span><br><span class="line">        h1 = b64.indexOf(<span class="keyword">data</span>.charAt(i++));</span><br><span class="line">        h2 = b64.indexOf(<span class="keyword">data</span>.charAt(i++));</span><br><span class="line">        h3 = b64.indexOf(<span class="keyword">data</span>.charAt(i++));</span><br><span class="line">        h4 = b64.indexOf(<span class="keyword">data</span>.charAt(i++));</span><br><span class="line">        bits = h1 &lt;&lt; <span class="number">18</span> | h2 &lt;&lt; <span class="number">12</span> | h3 &lt;&lt; <span class="number">6</span> | h4;</span><br><span class="line">        o1 = bits &gt;&gt; <span class="number">16</span> &amp; <span class="number">0xff</span>;</span><br><span class="line">        o2 = bits &gt;&gt; <span class="number">8</span> &amp; <span class="number">0xff</span>;</span><br><span class="line">        o3 = bits &amp; <span class="number">0xff</span>;</span><br><span class="line">        <span class="keyword">if</span> (h3 == <span class="number">64</span>) &#123;</span><br><span class="line">            tmp_arr[ac++] = String.fromCharCode(o1);</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (h4 == <span class="number">64</span>) &#123;</span><br><span class="line">            tmp_arr[ac++] = String.fromCharCode(o1, o2);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">while</span> (i &lt; <span class="keyword">data</span>.length);</span><br><span class="line">    dec = tmp_arr.join(<span class="string">''</span>);</span><br><span class="line">    dec = utf8_decode(dec);</span><br><span class="line">    <span class="keyword">return</span> dec;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>实现utf8解码</li>
</ol>
<figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">function utf8_decode(str_data)&#123;</span><br><span class="line">    var tmp_arr = [],i = <span class="number">0</span>,ac = <span class="number">0</span>,c1 = <span class="number">0</span>,c2 = <span class="number">0</span>,c3 = <span class="number">0</span>;str_data += '';</span><br><span class="line">    while (i &lt; str_data.length) &#123;</span><br><span class="line">        c1 = str_data.charCodeAt(i);</span><br><span class="line">        if (c1 &lt; <span class="number">128</span>) &#123;</span><br><span class="line">            tmp_arr[ac++] = String.fromCharCode(c1);</span><br><span class="line">            i++;</span><br><span class="line">        &#125; else if (c1 &gt; <span class="number">191</span> &amp;&amp; c1 &lt; <span class="number">224</span>) &#123;</span><br><span class="line">            c2 = str_data.charCodeAt(i + <span class="number">1</span>);</span><br><span class="line">            tmp_arr[ac++] = String.fromCharCode(((c1 &amp; <span class="number">31</span>) &lt;&lt; <span class="number">6</span>) | (c2 &amp; <span class="number">63</span>));</span><br><span class="line">            i += <span class="number">2</span>;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            c2 = str_data.charCodeAt(i + <span class="number">1</span>);</span><br><span class="line">            c3 = str_data.charCodeAt(i + <span class="number">2</span>);</span><br><span class="line">            tmp_arr[ac++] = String.fromCharCode(((c1 &amp; <span class="number">15</span>) &lt;&lt; <span class="number">12</span>) | ((c2 &amp; <span class="number">63</span>) &lt;&lt; <span class="number">6</span>) | (c3 &amp; <span class="number">63</span>));</span><br><span class="line">            i += <span class="number">3</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    return tmp_arr.join('');</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>半角转换为全角函数</li>
</ol>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">function ToDBC(<span class="built_in">str</span>)&#123;</span><br><span class="line">    var result = <span class="string">''</span>;</span><br><span class="line">    <span class="keyword">for</span>(var i=<span class="number">0</span>; i &lt; <span class="built_in">str</span>.length; i++)&#123;</span><br><span class="line">        code = <span class="built_in">str</span>.charCodeAt(i);</span><br><span class="line">        <span class="keyword">if</span>(code &gt;= <span class="number">33</span> &amp;&amp; code &lt;= <span class="number">126</span>)&#123;</span><br><span class="line">            result += <span class="keyword">String</span>.fromCharCode(<span class="built_in">str</span>.charCodeAt(i) + <span class="number">65248</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (code == <span class="number">32</span>)&#123;</span><br><span class="line">            result += <span class="keyword">String</span>.fromCharCode(<span class="built_in">str</span>.charCodeAt(i) + <span class="number">12288</span> - <span class="number">32</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            result += <span class="built_in">str</span>.charAt(i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>全角转换为半角函数</li>
</ol>
<figure class="highlight processing"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">function ToCDB(<span class="built_in">str</span>)&#123;</span><br><span class="line">    var result = <span class="string">''</span>;</span><br><span class="line">    <span class="keyword">for</span>(var i=<span class="number">0</span>; i &lt; <span class="built_in">str</span>.length; i++)&#123;</span><br><span class="line">        code = <span class="built_in">str</span>.charCodeAt(i);</span><br><span class="line">        <span class="keyword">if</span>(code &gt;= <span class="number">65281</span> &amp;&amp; code &lt;= <span class="number">65374</span>)&#123;</span><br><span class="line">            result += <span class="keyword">String</span>.fromCharCode(<span class="built_in">str</span>.charCodeAt(i) - <span class="number">65248</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span> (code == <span class="number">12288</span>)&#123;</span><br><span class="line">            result += <span class="keyword">String</span>.fromCharCode(<span class="built_in">str</span>.charCodeAt(i) - <span class="number">12288</span> + <span class="number">32</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            result += <span class="built_in">str</span>.charAt(i);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>用正则表达式清除html代码中的脚本</li>
</ol>
<figure class="highlight tex"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">function clear_script(html)&#123;</span><br><span class="line">    return html.replace(/&lt;script.*?&gt;[<span class="tag">\<span class="name">s</span></span><span class="tag">\<span class="name">S</span></span>]*?&lt;<span class="tag">\<span class="name">/</span></span>script&gt;|<span class="tag">\<span class="name">s</span></span>+on[a-zA-Z]&#123;3,16&#125;<span class="tag">\<span class="name">s</span></span>?=<span class="tag">\<span class="name">s</span></span>?"[<span class="tag">\<span class="name">s</span></span><span class="tag">\<span class="name">S</span></span>]*?"|<span class="tag">\<span class="name">s</span></span>+on[a-zA-Z]&#123;3,16&#125;<span class="tag">\<span class="name">s</span></span>?=<span class="tag">\<span class="name">s</span></span>?'[<span class="tag">\<span class="name">s</span></span><span class="tag">\<span class="name">S</span></span>]*?'|<span class="tag">\<span class="name">s</span></span>+on[a-zA-Z]&#123;3,16&#125;<span class="tag">\<span class="name">s</span></span>?=[^ &gt;]+/ig,"");</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>获取当前元素样式</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getStyle</span>(<span class="params">oElm, strCssRule</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> strValue = <span class="string">""</span>;</span><br><span class="line">    <span class="keyword">if</span>(<span class="built_in">document</span>.defaultView &amp;&amp; <span class="built_in">document</span>.defaultView.getComputedStyle)&#123;</span><br><span class="line">        strValue = <span class="built_in">document</span>.defaultView.getComputedStyle(oElm, <span class="string">""</span>).getPropertyValue(strCssRule);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span>(oElm.currentStyle)&#123;</span><br><span class="line">        strCssRule = strCssRule.replace(<span class="regexp">/\-(\w)/g</span>, <span class="function"><span class="keyword">function</span> (<span class="params">strMatch, p1</span>)</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> p1.toUpperCase();</span><br><span class="line">        &#125;);</span><br><span class="line">        strValue = oElm.currentStyle[strCssRule];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> strValue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="7">
<li>格式化CSS样式代码</li>
</ol>
<figure class="highlight taggerscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function formatCss(s)&#123;//格式化代码</span><br><span class="line">    s = s.replace(/<span class="symbol">\s</span>*([<span class="symbol">\&#123;</span><span class="symbol">\&#125;</span><span class="symbol">\:</span><span class="symbol">\;</span><span class="symbol">\,</span>])<span class="symbol">\s</span>*/g, "$1");</span><br><span class="line">    s = s.replace(/;<span class="symbol">\s</span>*;/g, ";"); //清除连续分号</span><br><span class="line">    s = s.replace(/<span class="symbol">\,</span>[<span class="symbol">\s</span><span class="symbol">\.</span><span class="symbol">\#</span><span class="symbol">\d</span>]*&#123;/g, "&#123;");</span><br><span class="line">    s = s.replace(/([^<span class="symbol">\s</span>])<span class="symbol">\&#123;</span>([^<span class="symbol">\s</span>])/g, "$1 &#123;<span class="symbol">\n</span><span class="symbol">\t</span>$2");</span><br><span class="line">    s = s.replace(/([^<span class="symbol">\s</span>])<span class="symbol">\&#125;</span>([^<span class="symbol">\n</span>]*)/g, "$1<span class="symbol">\n</span>&#125;<span class="symbol">\n</span>$2");</span><br><span class="line">    s = s.replace(/([^<span class="symbol">\s</span>]);([^<span class="symbol">\s</span><span class="symbol">\&#125;</span>])/g, "$1;<span class="symbol">\n</span><span class="symbol">\t</span>$2");</span><br><span class="line">    return s;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="8">
<li>压缩CSS样式代码</li>
</ol>
<figure class="highlight taggerscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">function compressCss (s) &#123;//压缩代码</span><br><span class="line">    s = s.replace(/<span class="symbol">\/</span><span class="symbol">\*</span>(.|<span class="symbol">\n</span>)*?<span class="symbol">\*</span><span class="symbol">\/</span>/g, ""); //删除注释</span><br><span class="line">    s = s.replace(/<span class="symbol">\s</span>*([<span class="symbol">\&#123;</span><span class="symbol">\&#125;</span><span class="symbol">\:</span><span class="symbol">\;</span><span class="symbol">\,</span>])<span class="symbol">\s</span>*/g, "$1");</span><br><span class="line">    s = s.replace(/<span class="symbol">\,</span>[<span class="symbol">\s</span><span class="symbol">\.</span><span class="symbol">\#</span><span class="symbol">\d</span>]*<span class="symbol">\&#123;</span>/g, "&#123;"); //容错处理</span><br><span class="line">    s = s.replace(/;<span class="symbol">\s</span>*;/g, ";"); //清除连续分号</span><br><span class="line">    s = s.match(/^<span class="symbol">\s</span>*(<span class="symbol">\S</span>+(<span class="symbol">\s</span>+<span class="symbol">\S</span>+)*)<span class="symbol">\s</span>*$/); //去掉首尾空白</span><br><span class="line">    return (s == null) ? "" : s[1];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="9">
<li>常用的正则表达式</li>
</ol>
<figure class="highlight markdown"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">//正整数</span><br><span class="line">/^[<span class="string">0-9</span>]<span class="emphasis">*[1-9][0-9]*</span>$/;</span><br><span class="line">//负整数</span><br><span class="line">/^-[<span class="string">0-9</span>]<span class="emphasis">*[1-9][0-9]*</span>$/;</span><br><span class="line">//正浮点数</span><br><span class="line">/^(([<span class="string">0-9</span>]+\.[<span class="string">0-9</span>]<span class="emphasis">*[1-9][0-9]*</span>)|([<span class="string">0-9</span>]<span class="emphasis">*[1-9][0-9]*</span>\.[<span class="string">0-9</span>]+)|([<span class="string">0-9</span>]<span class="emphasis">*[1-9][0-9]*</span>))$/;</span><br><span class="line">//负浮点数</span><br><span class="line">/^(-(([<span class="string">0-9</span>]+\.[<span class="string">0-9</span>]<span class="emphasis">*[1-9][0-9]*</span>)|([<span class="string">0-9</span>]<span class="emphasis">*[1-9][0-9]*</span>\.[<span class="string">0-9</span>]+)|([<span class="string">0-9</span>]<span class="emphasis">*[1-9][0-9]*</span>)))$/;</span><br><span class="line">//浮点数</span><br><span class="line">/^(-?\d+)(\.\d+)?$/;</span><br><span class="line">//email地址</span><br><span class="line">/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;</span><br><span class="line">//url地址</span><br><span class="line">/^[a-zA-z]+://(\w+(-\w+)<span class="emphasis">*)(\.(\w+(-\w+)*</span>))<span class="emphasis">*(\?\S*</span>)?$/;</span><br><span class="line">或：^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&amp;_~`@[\]\':+!]<span class="emphasis">*([^&lt;&gt;\"\"])*</span>$</span><br><span class="line">//年/月/日（年-月-日、年.月.日）</span><br><span class="line">/^(19|20)\d\d[<span class="string">- /.</span>](<span class="link">0[1-9]|1[012]</span>)[<span class="string">- /.</span>](<span class="link">0[1-9]|[12][0-9]|3[01]</span>)$/;</span><br><span class="line">//匹配中文字符</span><br><span class="line">/[\u4e00-\u9fa5]/;</span><br><span class="line">//匹配帐号是否合法(字母开头，允许5-10字节，允许字母数字下划线)</span><br><span class="line">/^[<span class="string">a-zA-Z</span>][<span class="symbol">a-zA-Z0-9_</span>]&#123;4,9&#125;$/;</span><br><span class="line">//匹配空白行的正则表达式</span><br><span class="line">/\n\s*\r/;</span><br><span class="line">//匹配中国邮政编码</span><br><span class="line">/[1-9]\d&#123;5&#125;(?!\d)/;</span><br><span class="line">//匹配身份证</span><br><span class="line">/\d&#123;15&#125;|\d&#123;18&#125;/;</span><br><span class="line">//匹配国内电话号码</span><br><span class="line">/(\d&#123;3&#125;-|\d&#123;4&#125;-)?(\d&#123;8&#125;|\d&#123;7&#125;)?/;</span><br><span class="line">//匹配IP地址</span><br><span class="line">/((2[0-4]\d|25[0-5]|[01]?\d\d?)\.)&#123;3&#125;(2[0-4]\d|25[0-5]|[01]?\d\d?)/;</span><br><span class="line">//匹配首尾空白字符的正则表达式</span><br><span class="line">/^\s<span class="emphasis">*|\s*</span>$/;</span><br><span class="line">//匹配HTML标记的正则表达式</span><br><span class="line">&lt; (\S*?)[^&gt;]<span class="emphasis">*&gt;.*</span>?|&lt; .*? /&gt;;</span><br><span class="line">//sql 语句</span><br><span class="line">^(select|drop|delete|create|update|insert).*$</span><br><span class="line">//提取信息中的网络链接</span><br><span class="line">(h|H)(r|R)(e|E)(f|F) <span class="emphasis">*= *</span>('|")?(\w|\\|\/|\.)+('|"| *|&gt;)?</span><br><span class="line">//提取信息中的邮件地址</span><br><span class="line">\w+([-+.]\w+)<span class="emphasis">*@\w+([-.]\w+)*</span>\.\w+([-.]\w+)*</span><br><span class="line">//提取信息中的图片链接</span><br><span class="line">(s|S)(r|R)(c|C) <span class="emphasis">*= *</span>('|")?(\w|\\|\/|\.)+('|"| *|&gt;)?</span><br><span class="line">//提取信息中的 IP 地址</span><br><span class="line">(\d+)\.(\d+)\.(\d+)\.(\d+)</span><br><span class="line">//取信息中的中国手机号码</span><br><span class="line">(86)<span class="emphasis">*0*</span>13\d&#123;9&#125;</span><br><span class="line">//提取信息中的中国邮政编码</span><br><span class="line">[1-9]&#123;1&#125;(\d+)&#123;5&#125;</span><br><span class="line">//提取信息中的浮点数（即小数）</span><br><span class="line">(-?\d*)\.?\d+</span><br><span class="line">//提取信息中的任何数字</span><br><span class="line">(-?\d*)(\.\d+)?</span><br><span class="line">//电话区号</span><br><span class="line">^0\d&#123;2,3&#125;$</span><br><span class="line">//腾讯 QQ 号</span><br><span class="line">^[<span class="string">1-9</span>]<span class="emphasis">*[1-9][0-9]*</span>$</span><br><span class="line">//帐号（字母开头，允许 5-16 字节，允许字母数字下划线）</span><br><span class="line">^[<span class="string">a-zA-Z</span>][<span class="symbol">a-zA-Z0-9_</span>]&#123;4,15&#125;$</span><br><span class="line">//中文、英文、数字及下划线</span><br><span class="line">^[\u4e00-\u9fa5_a-zA-Z0-9]+$</span><br></pre></td></tr></table></figure>
<ol start="10">
<li>格式化数字、金额</li>
</ol>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">number_format</span>(<span class="params"><span class="built_in">number</span>, decimals, dec_point, thousands_sep</span>) </span>&#123;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    * 参数说明：</span></span><br><span class="line"><span class="comment">    * number：要格式化的数字</span></span><br><span class="line"><span class="comment">    * decimals：保留几位小数</span></span><br><span class="line"><span class="comment">    * dec_point：小数点符号</span></span><br><span class="line"><span class="comment">    * thousands_sep：千分位符号</span></span><br><span class="line"><span class="comment">    * */</span></span><br><span class="line">    <span class="built_in">number</span> = (<span class="built_in">number</span> + <span class="string">''</span>).replace(<span class="regexp">/[^0-9+-Ee.]/g</span>, <span class="string">''</span>);</span><br><span class="line">    <span class="keyword">var</span> n = !<span class="built_in">isFinite</span>(+<span class="built_in">number</span>) ? <span class="number">0</span> : +<span class="built_in">number</span>,</span><br><span class="line">        prec = !<span class="built_in">isFinite</span>(+decimals) ? <span class="number">0</span> : <span class="built_in">Math</span>.abs(decimals),</span><br><span class="line">        sep = (<span class="keyword">typeof</span> thousands_sep === <span class="string">'undefined'</span>) ? <span class="string">','</span> : thousands_sep,</span><br><span class="line">        dec = (<span class="keyword">typeof</span> dec_point === <span class="string">'undefined'</span>) ? <span class="string">'.'</span> : dec_point,</span><br><span class="line">        s = <span class="string">''</span>,</span><br><span class="line">        toFixedFix = <span class="function"><span class="keyword">function</span> (<span class="params">n, prec</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> k = <span class="built_in">Math</span>.pow(<span class="number">10</span>, prec);</span><br><span class="line">            <span class="keyword">return</span> <span class="string">''</span> + <span class="built_in">Math</span>.ceil(n * k) / k;</span><br><span class="line">        &#125;;</span><br><span class="line"> </span><br><span class="line">    s = (prec ? toFixedFix(n, prec) : <span class="string">''</span> + <span class="built_in">Math</span>.round(n)).split(<span class="string">'.'</span>);</span><br><span class="line">    <span class="keyword">var</span> re = <span class="regexp">/(-?\d+)(\d&#123;3&#125;)/</span>;</span><br><span class="line">    <span class="keyword">while</span> (re.test(s[<span class="number">0</span>])) &#123;</span><br><span class="line">        s[<span class="number">0</span>] = s[<span class="number">0</span>].replace(re, <span class="string">"$1"</span> + sep + <span class="string">"$2"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">    <span class="keyword">if</span> ((s[<span class="number">1</span>] || <span class="string">''</span>).length &lt; prec) &#123;</span><br><span class="line">        s[<span class="number">1</span>] = s[<span class="number">1</span>] || <span class="string">''</span>;</span><br><span class="line">        s[<span class="number">1</span>] += <span class="keyword">new</span> <span class="built_in">Array</span>(prec - s[<span class="number">1</span>].length + <span class="number">1</span>).join(<span class="string">'0'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> s.join(dec);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> num = number_format(<span class="number">1234567.089</span>, <span class="number">2</span>, <span class="string">"."</span>, <span class="string">","</span>);<span class="comment">//1,234,567.09</span></span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/JavaScript/" rel="tag"># JavaScript</a>
          
            <a href="/blog/tags/前端/" rel="tag"># 前端</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2016/09/05/技术/JS技巧手记（二）/" rel="prev" title="JS原生技巧手记(二)">
                JS原生技巧手记(二) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/blog/images/avatar.png" alt="Geron Zhang">
            
              <p class="site-author-name" itemprop="name">Geron Zhang</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">12</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ZhangLorne" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:long642977312@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="/images/ecode.jpg" target="_blank" title="Wechat">
                      
                        <i class="fa fa-fw fa-wechat"></i>Wechat</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://instagram.com/Funny291" target="_blank" title="Instagram">
                      
                        <i class="fa fa-fw fa-instagram"></i>Instagram</a>
                  </span>
                
            </div>
          
          
          <iframe allowtransparency src="/blog/images/mp3.html?rel=0&amp;autoplay=1" frameborder="0" scrolling="no" width="100%">
          </iframe>

          
          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2016 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Geron Zhang</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'c4Wwl9tIGuNGAWpUVALEhMLL-gzGzoHsz',
        appKey: '73Ylo6XQCclsDBYq5aGsT70K',
        placeholder: '（建议在上方留下昵称和邮箱等信息，以便收到回复通知）',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("c4Wwl9tIGuNGAWpUVALEhMLL-gzGzoHsz", "73Ylo6XQCclsDBYq5aGsT70K");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
